<template>
  <el-card class="box-card">
    <el-form
      ref="formRef"
      :label-position="'top'"
      label-width="160px"
      :model="formData"
      :rules="formRules"
      v-loading="isLoading"
    >
      <el-alert
        type="info"
        :closable="false"
        show-icon
        title="计划任务"
        description="开启后，按照时间间隔执行"
        style="margin-bottom: 20px"
      />
      <el-form-item prop="task_status">
        <el-switch
          v-model="formData.task_status"
          :active-value="1"
          :inactive-value="0"
          active-color="#13ce66"
          inactive-color="#ff4949"
        />
      </el-form-item>

      <el-alert
        type="info"
        :closable="false"
        show-icon
        title="计划任务 - 自动取消订单"
        description="设置后，将在规定时间内释放未付款的订单"
        style="margin-bottom: 20px"
      />
      <el-form-item prop="order_cancel_valid">
        <el-input-number
          v-model="formData.order_cancel_valid"
          :min="1000"
          :step="1000"
          step-strictly
          :controls="false"
        />
        <span>（毫秒），自动换算等于</span>
        <span>{{ formatSecondsToDay(formData.order_cancel_valid) }}</span>
      </el-form-item>

      <el-alert
        type="info"
        :closable="false"
        show-icon
        title="计划任务 - 自动收货"
        description="设置后，将在规定时间内，自动将订单状态改为已收货"
        style="margin-bottom: 20px"
      />
      <el-form-item prop="order_take_valid">
        <el-input-number
          v-model="formData.order_take_valid"
          :min="1000"
          :step="1000"
          step-strictly
          :controls="false"
        />
        <span>（毫秒），自动换算等于</span>
        <span>{{ formatSecondsToDay(formData.order_take_valid) }}</span>
      </el-form-item>

      <el-alert
        type="info"
        :closable="false"
        show-icon
        title="计划任务 - 自动完成"
        description="设置后，将在规定时间内，自动将订单状态改为已完成"
        style="margin-bottom: 20px"
      />
      <el-form-item prop="order_complete_valid">
        <el-input-number
          v-model="formData.order_complete_valid"
          :min="1000"
          :step="1000"
          step-strictly
          :controls="false"
        />
        <span>（毫秒），自动换算等于</span>
        <span>{{ formatSecondsToDay(formData.order_complete_valid) }}</span>
      </el-form-item>

      <el-alert
        type="info"
        :closable="false"
        show-icon
        title="计划任务 - 自动完成售后"
        description="设置后，将在规定时间内，自动完成售后订单收益结算"
        style="margin-bottom: 20px"
      />
      <el-form-item prop="appeal_complete_valid">
        <el-input-number
          v-model="formData.appeal_complete_valid"
          :min="1000"
          :step="1000"
          step-strictly
          :controls="false"
        />
        <span>（毫秒），自动换算等于</span>
        <span>{{ formatSecondsToDay(formData.appeal_complete_valid) }}</span>
      </el-form-item>

      <el-alert
        type="info"
        :closable="false"
        show-icon
        title="计划任务 - 自动同意提现"
        description="设置后，将在规定时间内，自动同意会员的提现申请"
        style="margin-bottom: 20px"
      />
      <el-form-item prop="capital_confirm_valid">
        <el-input-number
          v-model="formData.capital_confirm_valid"
          :min="1000"
          :step="1000"
          step-strictly
          :controls="false"
        />
        <span>（毫秒），自动换算等于</span>
        <span>{{ formatSecondsToDay(formData.capital_confirm_valid) }}</span>
      </el-form-item>

      <el-divider />

      <el-alert
        type="warning"
        :closable="false"
        show-icon
        description="所有计划任务间隔：每整30秒，执行一次"
        style="margin-bottom: 20px"
      />
      <div>
        <el-button link @click="handleClickUseDefault()"
          >使用默认配置</el-button
        >
        <PipeResetBtn
          :formEl="formRef"
          @clear="handleClickReset"
          :loading="isLoading"
          >取消修改</PipeResetBtn
        >
        <el-button
          type="primary"
          @click="handleClickSubmit(formRef)"
          :loading="isLoading"
          >保存修改</el-button
        >
      </div>
    </el-form>
  </el-card>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import type { ElForm } from 'element-plus';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getSystemKvDetail, updateSystemKv } from '@/apis/system-kv';
import { loopPropAssignment } from '@/utils/util';

// 加载状态
const isLoading = ref(false);

// 表单 - ref
const formRef = ref<InstanceType<typeof ElForm>>();

interface FormData {
  /** 是否执行计划任务 */
  task_status: 0 | 1;
  /** 订单-自动取消-有效时间（毫秒） */
  order_cancel_valid: number;
  /** 订单-自动收货-有效时间（毫秒） */
  order_take_valid: number;
  /** 订单-自动完成-有效时间（毫秒） */
  order_complete_valid: number;
  /** 售后订单-自动完成-有效时间（毫秒） */
  appeal_complete_valid: number;
  /** 提现-自动同意-有效时间（毫秒） */
  capital_confirm_valid: number;
}

// 表单数据
const GetFormData = (): FormData => ({
  task_status: 1,
  order_cancel_valid: 60 * 60 * 1000,
  order_take_valid: 7 * 24 * 60 * 60 * 1000,
  order_complete_valid: 3 * 24 * 60 * 60 * 1000,
  appeal_complete_valid: 3 * 24 * 60 * 60 * 1000,
  capital_confirm_valid: 30 * 1000
});
const formData = reactive(GetFormData());

const formRules = reactive({
  order_cancel_valid: [
    { required: true, trigger: 'blur', message: '请输入时间' }
  ],
  order_take_valid: [
    { required: true, trigger: 'blur', message: '请输入时间' }
  ],
  order_complete_valid: [
    { required: true, trigger: 'blur', message: '请输入时间' }
  ],
  appeal_complete_valid: [
    { required: true, trigger: 'blur', message: '请输入时间' }
  ],
  capital_confirm_valid: [
    { required: true, trigger: 'blur', message: '请输入时间' }
  ]
});

// 详情
const detailData = ref<API.systemKv.EntitySchema>();

// 将毫秒转换时间
const formatSecondsToDay = (millisecond: number) => {
  let seconds = millisecond / 1000;

  let days = Math.floor(seconds / (24 * 60 * 60));
  seconds %= 24 * 60 * 60;
  let hours = Math.floor(seconds / (60 * 60));
  seconds %= 60 * 60;
  let minutes = Math.floor(seconds / 60);
  seconds %= 60;

  return `${days}天 ${hours}小时 ${minutes}分钟 ${seconds}秒`;
};

// btn - use default
const handleClickUseDefault = () => {
  // 使用默认值
  loopPropAssignment(formData, GetFormData());
};

// btn - reset
const handleClickReset = () => {
  requestDataDetail();
};

// btn - submit
const handleClickSubmit = async (
  formEl: InstanceType<typeof ElForm> | undefined
) => {
  // 二次确认
  try {
    await ElMessageBox.confirm(
      '设置后，所有计划任务立即生效，是否设置？',
      '设置计划任务',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
  } catch (error) {
    return;
  }

  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (!valid) return;

    submitDataUpdate();
  });
};

// submit - update
const submitDataUpdate = () => {
  const dataOpt = {
    value: JSON.stringify(formData),
    remark: detailData.value?.remark
  };

  isLoading.value = true;
  updateSystemKv(detailData.value?.key!, dataOpt)
    .then((res) => {
      isLoading.value = false;
      ElMessage.success(res.message);
    })
    .catch(() => {
      isLoading.value = false;
    });
};

const requestDataDetail = () => {
  isLoading.value = true;
  getSystemKvDetail('system_plan')
    .then((res) => {
      isLoading.value = false;
      detailData.value = res.data;
      const resData = JSON.parse(res.data?.value ?? '{}');
      // 初始化数据
      loopPropAssignment(formData, resData);
    })
    .catch(() => {
      isLoading.value = false;
    });
};

requestDataDetail();
</script>

<style lang="scss" scoped></style>
